package com.easy.interceptor;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.easy.util.Result;
import com.easy.util.SYS;
import com.easy.util.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

/**
 * 拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws IOException {
        //获取token
        String token = request.getHeader(SYS.TOKEN_AUTHORIZATION);
        //判断token是否有效
        if(token==null||!TokenUtil.verify(token)){
//            response.setStatus(401);
            Result result = new Result(401,"认证异常",null);
            String json = JSONUtil.toJsonStr(result);
//            json=JSON.toJSONString(result);
            response.getWriter().println(json);
            return false;
        }
        //返回结果
        return true;
    }
}
